package org.jeecg.common.oa.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.oa.entity.OaPending;
import org.jeecg.common.oa.enums.PendingStateEnum;
import org.jeecg.common.oa.service.IOaPendingService;
import org.jeecg.common.oa.vo.OaPendingVo;
import org.jeecg.common.properties.config.OaPropertyConfig;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

@Configuration
@Slf4j
public class OaPendingUtils {

    @Autowired
    private OaPropertyConfig oaPropertyConfigBase;
    @Autowired
    private IOaPendingService oaPendingServiceBase;

    //当前工具类
    private static OaPropertyConfig oaPropertyConfig;
    private static IOaPendingService oaPendingService;

    //解决静态方法中不能直接用oaConfig的问题
    @PostConstruct
    public void init() {
        oaPropertyConfig = this.oaPropertyConfigBase;
        oaPendingService = this.oaPendingServiceBase;
    }

    /**
     * 发送审批提醒待办
     * @param fromUser
     * @param toUser
     * @param title
     * @param taskId
     * @param state
     * @param subState
     */
    public static void sendRemindPending(LoginUser fromUser, LoginUser toUser, String title, String taskId, Integer state, Integer subState) {
        sendPending(fromUser, toUser, title, taskId, state, subState, oaPropertyConfig.getPendingURL().replace("{CURRENT_ID}", taskId),
                oaPropertyConfig.getPendingH5URL().replace("{CURRENT_ID}", taskId));
    }
    public static void sendRemindPending(LoginUser fromUser, LoginUser toUser, String title, String taskId) {
        sendPending(fromUser, toUser, title, taskId, PendingStateEnum.NOT_PROCESSED.getStatus(), null, oaPropertyConfig.getPendingURL().replace("{CURRENT_ID}", taskId),
                oaPropertyConfig.getPendingH5URL().replace("{CURRENT_ID}", taskId));
    }

    public static void sendRemindPendingList(LoginUser fromUser, List<LoginUser> toUsers, String title, String taskId) {
        sendRemindPendingList(fromUser, toUsers, title, taskId, PendingStateEnum.NOT_PROCESSED.getStatus(), null);
    }
    /**
     * 发送审批提醒待办列表
     * @param fromUser
     * @param toUsers
     * @param title
     * @param taskId
     * @param state
     * @param subState
     */
    public static void sendRemindPendingList(LoginUser fromUser, List<LoginUser> toUsers, String title, String taskId, Integer state, Integer subState) {
        sendPendingList(fromUser, toUsers, title, taskId, state, subState, oaPropertyConfig.getPendingURL().replace("{CURRENT_ID}", taskId),
                oaPropertyConfig.getPendingH5URL().replace("{CURRENT_ID}", taskId));
    }

    /**
     * 发送审批完成待办
     * @param fromUser
     * @param toUser
     * @param title
     * @param taskId
     * @param state
     * @param subState
     */
    public static void sendCompletePending(LoginUser fromUser, LoginUser toUser, String title, String taskId, Integer state, Integer subState) {
        sendPending(fromUser, toUser, title, taskId, state, subState, oaPropertyConfig.getCompletePendingURL(), oaPropertyConfig.getCompletePendingH5URL());
    }

    /**
     * 发送审批完成待办列表
     * @param fromUser
     * @param toUsers
     * @param title
     * @param taskId
     * @param state
     * @param subState
     */
    public static void sendCompletePendingList(LoginUser fromUser, List<LoginUser> toUsers, String title, String taskId, Integer state, Integer subState) {
        sendPendingList(fromUser, toUsers, title, taskId, state, subState, oaPropertyConfig.getCompletePendingURL(), oaPropertyConfig.getCompletePendingH5URL());
    }

    /**
     * 发送审批完成待办
     * @param taskId
     * @param subState
     */
    public static void sendCompletePending(String taskId, Integer subState) {
        sendPendingList(taskId, subState, oaPropertyConfig.getCompletePendingURL(), oaPropertyConfig.getCompletePendingH5URL());
    }

    /***
     * 单条发送待办到OA系统
     * @param fromUser
     * @param toUser
     * @param title
     * @param taskId
     * @param state
     * @param subState
     * @param pendingUrl
     * @param h5Url
     */
    public static void sendPending(LoginUser fromUser, LoginUser toUser, String title, String taskId, Integer state, Integer subState, String pendingUrl, String h5Url) {
//
//        if (StringUtils.isBlank(taskId)) {
//            return;
//        }
//        if (toUser == null || StringUtils.isBlank(toUser.getId())) {
//            return;
//        }
//        if (fromUser == null || StringUtils.isBlank(fromUser.getId())) {
//            return;
//        }
//        if (toUser.getType() == null || toUser.getType().intValue() != DataSourcesTypeEnum.OA.getStatus()){
//            return;
//        }
//        OaPending oaPending = createOaPending(fromUser, toUser, title, taskId, state, subState, pendingUrl, h5Url);
//        OaPendingVo msg = createOaPendingVo(oaPending);
//        String url = oaPropertyConfig.getSendPending().replace("{TOKEN}", OaSyncUtils.getToke(false));
//        String resultString = null;
//        try {
//            resultString = HttpClientUtil.doPostJson(url, JSONObject.toJSONString(msg));
//            log.info("resultString：", resultString);
//            ResultEntity resultEntity = JSONObject.parseObject(resultString, ResultEntity.class);
//            if (resultEntity.getSuccess()) {
//                oaPending.setStatus(ResultStatusEnum.SUCCESS.getStatus());
//            } else {
//                oaPending.setStatus(ResultStatusEnum.FAIL.getStatus());
//            }
//            oaPendingService.updateById(oaPending);
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("单条发送待办，回写待办发送状态失败:", resultString);
//        }

    }

    /**
     *
     * 群发待办到OA系统
     * @param fromUser
     * @param toUsers
     * @param title
     * @param taskId
     * @param state
     * @param subState
     * @param pendingUrl
     * @param h5Url
     */
    public static void sendPendingList(LoginUser fromUser, List<LoginUser> toUsers, String title, String taskId, Integer state, Integer subState, String pendingUrl, String h5Url) {

//        if (StringUtils.isBlank(taskId)) {
//            return;
//        }
//        if (fromUser == null || StringUtils.isBlank(fromUser.getId())) {
//            return;
//        }
//        if (toUsers == null || toUsers.size() == 0) {
//            return;
//        }
//        List<OaPendingVo> pendingVos = new ArrayList<>();
//        List<String> ids = new ArrayList<>();
//        OaPending oaPending = null;
//        for (LoginUser toUser : toUsers) {
//            if (toUser.getType() == null || toUser.getType().intValue() != DataSourcesTypeEnum.OA.getStatus()){
//                continue;
//            }
//            oaPending = createOaPending(fromUser, toUser, title, taskId, state, subState, pendingUrl, h5Url);
//            OaPendingVo msg = createOaPendingVo(oaPending);
//            pendingVos.add(msg);
//            ids.add(oaPending.getId());
//        }
//        if (pendingVos.size() == 0){
//            return;
//        }
//        pendingList(ids, pendingVos);

    }

    /**
     *
     * 群发待办到OA系统
     * @param taskId
     * @param subState
     * @param pendingUrl
     * @param h5Url
     */
    public static void sendPendingList(String taskId, Integer subState, String pendingUrl, String h5Url) {

//        if (subState == null || StringUtils.isBlank(taskId)) {
//            return;
//        }
//        OaPending oaPending = new OaPending();
//        oaPending.setTaskId(taskId);
//        oaPending.setState(PendingStateEnum.NOT_PROCESSED.getStatus());
//        oaPending.setStatus(ResultStatusEnum.SUCCESS.getStatus());
//        QueryWrapper<OaPending> queryWrapper = new QueryWrapper<>(oaPending);
//        List<OaPending> pendingList = oaPendingService.list(queryWrapper);
//        List<OaPendingVo> pendingVos = new ArrayList<>();
//        if (pendingList == null || pendingList.size() == 0){
//            return;
//        }
//        List<String> ids = new ArrayList<>();
//        for (OaPending pending : pendingList){
//            pending.setState(PendingStateEnum.PROCESSED.getStatus());
//            pending.setSubState(subState);
//            pending.setUrl(pendingUrl);
//            pending.setH5Url(h5Url);
//            pending.setStatus(ResultStatusEnum.UNKNOWN.getStatus());
//            oaPendingService.updateById(pending);
//            OaPendingVo msg = createOaPendingVo(pending);
//            pendingVos.add(msg);
//            ids.add(oaPending.getId());
//        }
//        pendingList(ids, pendingVos);
    }

    private static void pendingList(List<String> ids, List<OaPendingVo> pendingVos){
//        String url = oaPropertyConfig.getSendPendingList().replace("{TOKEN}", OaSyncUtils.getToke(false));
//        Map<String, Object> param = new HashMap<>();
//        param.put("pendingList", pendingVos);
//        String resultString = null;
//        try {
//            resultString = HttpClientUtil.doPostJson(url, JSONObject.toJSONString(param));
//            log.info("resultString：", resultString);
//            ResultEntity resultEntity = JSONObject.parseObject(resultString, ResultEntity.class);
//            LambdaUpdateWrapper<OaPending> updateWrapper = new LambdaUpdateWrapper<>();
//            updateWrapper.in(OaPending::getId, ids);
//            OaPending pending = new OaPending();
//            if (resultEntity.getSuccess()) {
//                pending.setStatus(ResultStatusEnum.SUCCESS.getStatus());
//            } else {
//                pending.setStatus(ResultStatusEnum.FAIL.getStatus());
//            }
////            updateWrapper.setEntity(pending);
//            oaPendingService.update(pending, updateWrapper);
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("群发送待办完成，回写待办发送状态失败:", resultString);
//        }
    }

    /**
     *
     * 创建待办保存到数据库
     * @param fromUser
     * @param toUser
     * @param title
     * @param taskId
     * @param state
     * @param subState
     * @param pendingUrl
     * @param h5Url
     * @return
     */
    private static OaPending createOaPending(LoginUser fromUser, LoginUser toUser, String title, String taskId, Integer state, Integer subState, String pendingUrl, String h5Url) {
        OaPending pending = new OaPending();
//        pending.setRegisterCode(oaPropertyConfig.getRegisterCode());
//        pending.setTitle(title);
//        pending.setTaskId(taskId);
//        pending.setSenderId(fromUser.getId());// 用户的唯一标识
//        pending.setReceiverId(toUser.getId());//接收用户的唯一标识
//        pending.setSenderName(fromUser.getRealname());
//        pending.setReceiverName(toUser.getRealname());
//        pending.setNoneBindingReceiver(toUser.getUsername());
//        pending.setNoneBindingSender(fromUser.getUsername());
//        pending.setCreationDate(DateUtils.now());
//        // 参考接口说明，致远提供
//        pending.setState(state);
//        pending.setSubState(subState);
//        pending.setContent(oaPropertyConfig.getDownloadUrl());
//        pending.setUrl(pendingUrl);
//        pending.setH5Url(h5Url);
//        oaPendingService.save(pending);
        return pending;
    }

    /**
     * 创建发送待办对象
     *
     * @param oaPending
     * @return
     */
    private static OaPendingVo createOaPendingVo(OaPending oaPending) {
        OaPendingVo pendingVo = new OaPendingVo();
//        pendingVo.setRegisterCode(oaPending.getRegisterCode());
//        pendingVo.setTaskId(oaPending.getId());  // 你们系统的唯一标识
//        pendingVo.setTitle(oaPending.getTitle());
//        pendingVo.setThirdSenderId(oaPending.getSenderId());// 用户的唯一标识
//        pendingVo.setThirdReceiverId(oaPending.getReceiverId());//接收用户的唯一标识
//        pendingVo.setSenderName(oaPending.getSenderName());
//        pendingVo.setThirdReceiverName(oaPending.getReceiverName());
//        pendingVo.setNoneBindingReceiver(oaPending.getNoneBindingReceiver());
//        pendingVo.setNoneBindingSender(oaPending.getNoneBindingSender());
//        pendingVo.setCreationDate(oaPending.getCreationDate());
//        // 参考接口说明，致远提供
//        pendingVo.setState(oaPending.getState());
//        pendingVo.setSubState(oaPending.getSubState());
//        pendingVo.setContent(oaPending.getContent());
//        pendingVo.setUrl(oaPending.getUrl());   //处理地址
//        pendingVo.setH5url(oaPending.getH5Url());
        return pendingVo;
    }


    public static void testSendPending() {
        OaPendingVo pendingVo = new OaPendingVo();
        pendingVo.setTaskId("30011111");  // 你们系统的唯一标识
        pendingVo.setRegisterCode("3001");      //我们系统提供
        pendingVo.setTitle("关于学习十八大精神的会议纪要1");
        pendingVo.setThirdSenderId("test");  // 改成发送用户的登录名
        pendingVo.setSenderName("测试");  // 改成发送用户的登录名
        pendingVo.setThirdReceiverId("test"); //消息接收者的登录名
        pendingVo.setThirdReceiverName("测试"); //消息接收者的登录名
        pendingVo.setNoneBindingReceiver("test");
        pendingVo.setNoneBindingSender("test");
        pendingVo.setCreationDate(DateUtils.now());
        pendingVo.setState(1);
        pendingVo.setSubState(2);
        pendingVo.setUrl("http://www.baidu.com");   //处理地址
        pendingVo.setH5url("http://www.baidu.com");
//        pendingVo.setToken(token);

//        String url = oaConfig.getSendPending().replace("{TOKEN}", OaSyncUtils.getToke(false));
//        String url = "http://www.cqukon.com:8081/seeyon/rest/thirdPending/receive/singlePending?token=4b10897e-4d86-4745-9fd6-7a5b56ee5943";
        String url = "http://192.168.0.106/seeyon/rest/thirdpartyPending/receive?token=08f47ba6-66bd-475e-b1b8-dfc5088a219d";
        String resultString = HttpClientUtil.doPostJson(url, JSONObject.toJSONString(pendingVo));
        System.out.println(resultString);

    }


    public static void main(String[] args) {
        testSendPending();
    }

}
